输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例
1 2
| 输入:head = [1,3,2] 输出:[2,3,1]
|
题解
这道题主体思想是访问链表中的元素并设法倒序输出结果。
方法一:递归法
利用递归的方法先递推至链表末端,在回溯时依次将节点值加入列表,即可实现链表值的倒序输出。
需要注意的是:
- 程序总是要有执行完毕的时候,当
head == nullptr时,代表超越了链表尾节点,返回空列表
时间复杂度:遍历链表,递归N次。
空间复杂度:系统递归需要使用O(N)的栈空间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: vector<int> reversePrint(ListNode* head) { recur(head); return res; } private: vector<int> res; void recur(ListNode* head) { if(head == nullptr) return; recur(head->next); res.push_back(head->val); } };
|
方法二:迭代器反转法
链表只能从前往后访问每个节点,因为要倒序输出各节点值,所以我们也可以借助reverse()函数实现链表值的倒序输出。
需要注意的是:
- 当
head != nullptr时,从前往后依次访问节点并将其添加到res容器中去
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public: vector<int> reversePrint(ListNode* head) { vector<int> res; while(head != nullptr) { res.push_back(head->val); head = head->next; } reverse(res.begin(), res.end()); return res; } };
|
方法三:辅助栈法
链表只能从前往后访问每个节点,因为要倒序输出各节点值,我们可以借助栈来实现。
时间复杂度: 入栈和出栈共使用O(N)时间。
空间复杂度: 辅助栈 stack 和数组 res 共使用O(N)的额外空间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: vector<int> reversePrint(ListNode* head) { stack<int> stk; while(head != nullptr) { stk.push(head->val); head = head->next; } vector<int> res; while(!stk.empty()) { res.push_back(stk.top()); stk.pop(); } return res; } };
|